import React, { useState, useRef, useEffect } from 'react';
import { Button, Modal, Form, InputNumber, message } from 'antd';
import { ProTable, ProColumns, ActionType } from '@ant-design/pro-components';

const Order = () => {
    const tableRef = useRef(null);
    const [form] = Form.useForm();
    const [editingRecord, setEditingRecord] = useState(null);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [data, setData] = useState([
        {
            key: '1',
            StoreName: '店铺A',
            CustomerName: '顾客1',
            OrderDate: '2024-11-18',
            ProductName: '商品A',
            Specifications: '规格1',
            quantity: 10,
            Totalofproducts: '100元',
            Paymentstatus: true,
            discount: '5%',
            Aftertaxtotal: '95元',
            taxrate: '10%',
            Taxamount: '9.5元',
        },
        {
            key: '2',
            StoreName: '店铺B',
            CustomerName: '顾客2',
            OrderDate: '2024-11-17',
            ProductName: '商品B',
            Specifications: '规格2',
            quantity: 5,
            Totalofproducts: '50元',
            Paymentstatus: false,
            discount: '0%',
            Aftertaxtotal: '50元',
            taxrate: '10%',
            Taxamount: '5元',
        },
    ]);

    const columns = [
        {
            title: '店铺名称',
            dataIndex: 'StoreName',
            key: 'StoreName',
            search: true,
        },
        {
            title: '顾客名称',
            dataIndex: 'CustomerName',
            key: 'CustomerName',
            search: false,
        },
        {
            title: '订单日期',
            dataIndex: 'OrderDate',
            key: 'OrderDate',
            search: true,
            valueType: 'date',
        },
        {
            title: '商品名称',
            dataIndex: 'ProductName',
            key: 'ProductName',
            search: false,
        },
        {
            title: '规格',
            dataIndex: 'Specifications',
            key: 'Specifications',
            search: false,
        },
        {
            title: '数量',
            dataIndex: 'quantity',
            key: 'quantity',
            search: false,
        },
        {
            title: '商品合计',
            dataIndex: 'Totalofproducts',
            key: 'Totalofproducts',
            search: false,
        },
        {
            title: '支付状态',
            dataIndex: 'Paymentstatus',
            key: 'Paymentstatus',
            render: (_, record) => (record.Paymentstatus ? '已支付' : '未支付'),
            search: false,
        },
        {
            title: '操作',
            key: 'operation',
            render: (_, record) => (
                <div>
                    <Button
                        danger
                        style={{ marginRight: 8 }}
                        onClick={() => handleEdit(record)}
                    >
                        修改
                    </Button>
                    <Button>详情</Button>
                </div>
            ),
            search: false,
        },
    ];

    useEffect(() => {
        tableRef.current?.reload();
    }, [data]);

    const handleEdit = (record) => {
        setEditingRecord(record);
        setIsModalOpen(true);
        form.setFieldsValue({
            ...record,
            price: parseFloat(record.Totalofproducts.replace('元', '')) / record.quantity,
        });
    };

    const handleModalOk = (values) => {
        const updatedData = data.map((item) => {
            if (item.key === editingRecord?.key) {
                return {
                    ...item,
                    quantity: values.quantity,
                    Totalofproducts: `${(values.price * values.quantity).toFixed(2)}元`,
                };
            }
            return item;
        });

        setData(updatedData);
        message.success('修改成功！');
        setIsModalOpen(false);
        setEditingRecord(null);
        form.resetFields();
    };

    return (
        <>
            <ProTable
                actionRef={tableRef}
                columns={columns}
                defaultData={data}
                rowKey="key"
                pagination={{
                    pageSize: 10,
                }}
                request={async (params) => {
                    const filteredData = data.filter((item) => {
                        return Object.keys(params).every((key) => {
                            if (!params[key]) return true;
                            const value = params[key];
                            if (typeof value === 'string') {
                                return item[key]?.toString().includes(value);
                            }
                            return true;
                        });
                    });

                    return {
                        data: filteredData,
                        success: true,
                    };
                }}
            />
            <Modal
                title="修改订单"
                open={isModalOpen}
                onCancel={() => {
                    setIsModalOpen(false);
                    form.resetFields();
                }}
                footer={null}
            >
                <Form form={form} onFinish={handleModalOk}>
                    <Form.Item
                        label="数量"
                        name="quantity"
                        rules={[{ required: true, message: '请输入数量！' }]}
                    >
                        <InputNumber min={1} style={{ width: '100%' }} />
                    </Form.Item>
                    <Form.Item
                        label="单价"
                        name="price"
                        rules={[{ required: true, message: '请输入单价！' }]}
                    >
                        <InputNumber min={0.01} step={0.01} style={{ width: '100%' }} />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit" style={{ marginRight: 8 }}>
                            确定
                        </Button>
                        <Button
                            onClick={() => {
                                setIsModalOpen(false);
                                form.resetFields();
                            }}
                        >
                            取消
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>
        </>
    );
};

export default Order;
